package com.xhl.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xhl.service.CategoryService;

@Controller
@RequestMapping("/file")
public class FileUploadController {


    @Autowired
    CategoryService categoryService;


    // 图片显示
    @RequestMapping("/getImage")
    @ResponseBody
    public void getImagesId(HttpServletResponse rp) {
        String filePath = "D:\\Java\\webSpeace\\Tmall\\WebContent\\upload\\d204152f-c0b0-4a9f-b7e5-7a4dce93aa3e.jpg";
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = rp.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /*
     * // 图片上传
     *
     * @RequestMapping(value = "/upload", method = RequestMethod.POST)
     *
     * @ResponseBody // 不写会默认返回当前路径！！ public void upload(String username,
     * MultipartFile image, HttpServletRequest req) throws Exception, IOException {
     * System.out.println("username数据：" + username); // 接收文件数据
     * System.out.println(image.getContentType());// image/jpeg 获取上传文件的类型
     * System.out.println(image.getName());// image 获取file标签的name属性 <input
     * type="file" name="image" > System.out.println(image.getOriginalFilename());//
     * 1.jpg 获取上传文件的名称
     *
     * // 获取到上传的文件数据 String contentType = image.getContentType(); // 判断上传文件是否为图片 if
     * (contentType == null || !contentType.startsWith("image/")) {
     * System.out.println("===不属于图片类型...==="); return; }
     *
     * // 动态获取上传文件夹的路径 //ServletContext context = req.getServletContext(); // String
     * realPath = context.getRealPath("/upload");// 获取本地存储位置的绝对路径 String realPath =
     * "D:\\Java\\webSpeace\\Tmall\\WebContent\\upload";
     * System.out.println(realPath); String filename =
     * image.getOriginalFilename();// 获取上传时的文件名称 filename =
     * UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(filename);//
     * 创建一个新的文件名称 File f = new File(realPath, filename); image.transferTo(f);//
     * 将上传的文件存储到指定位置 }
     */

    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletRequest req, HttpServletResponse resp, String filename) throws Exception {
        String realPath = req.getServletContext().getRealPath("/download");// 获取下载文件的路径
        File file = new File(realPath, filename);// 把下载文件构成一个文件处理 filename:前台传过来的文件名称

        // 设置响应类型 ==》 告诉浏览器当前是下载操作，我要下载东西
        resp.setContentType("application/x-msdownload");
        // 设置下载时文件的显示类型(即文件名称-后缀) ex：txt为文本类型
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);

        // 下载文件：将一个路径下的文件数据转到一个输出流中，也就是把服务器文件通过流写(复制)到浏览器端
        Files.copy(file.toPath(), resp.getOutputStream());// Files.copy(要下载的文件的路径,响应的输出流)
    }

    /*
     * 下载方式二：Spring框架技术
     */
    @RequestMapping(value = "/download2", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(HttpServletRequest request, String filename) throws IOException {
        String realPath = request.getServletContext().getRealPath("/download");// 获取下载文件的路径
        File file = new File(realPath, filename);// 把下载文件构成一个文件处理 filename:前台传过来的文件名称

        HttpHeaders headers = new HttpHeaders();// 设置头信息
        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");// 设置响应的文件名

        headers.setContentDispositionFormData("attachment", downloadFileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // MediaType:互联网媒介类型 contentType：具体请求中的媒体类型信息
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /*
     * @RequestMapping(path = "/upload") public String upload(HttpServletRequest
     * request, MultipartFile upload) throws IllegalStateException, IOException { //
     * 使用fileupload组件完成文件上传 // 上传的位置 String path =
     * request.getSession().getServletContext().getRealPath("/uploads/"); //
     * 判断，该路径是否存在 File file = new File(path); if (!file.exists()) { // 创建该文件夹
     * file.mkdirs(); } // 获取上传文件的名称 String filename = upload.getOriginalFilename();
     * // 把文件的名称设置唯一值，uuid String uuid = UUID.randomUUID().toString().replace("-",
     * ""); filename = uuid + "_" + filename; // 完成文件上传 upload.transferTo(new
     * File(path, filename)); return "a"; }
     */

    @RequestMapping("/filesUpload")
    public String filesUpload(HttpServletRequest request, MultipartFile[] files)
            throws IllegalStateException, IOException {
        // 判断file数组不能为空并且长度大于0
        if (files != null && files.length > 0) {
            // 循环获取file数组中得文件
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                // 保存文件
                String path = request.getSession().getServletContext().getRealPath("/uploads/");
                // 判断，该路径是否存在
                File f = new File(path);
                if (!f.exists()) {
                    // 创建该文件夹
                    f.mkdirs();
                }
                // 获取上传文件的名称
                String filename = file.getOriginalFilename();
                // 把文件的名称设置唯一值，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + "_" + filename;
                // 完成文件上传
                file.transferTo(new File(path, filename));
            }
        }
        return "a";
    }
}
